package com.sdkj.fixed.asset.common.utils.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * OA工作流
 * 邮箱授权码：tLVrj3K63Rf6kjuM
 * 地址：oa@sdkeji.com
 * 密码：Swq7824310
 * 发件服务器：smtp.qiye.163.com
 * 发件端口=25
 */
@Component
public class MailUtils {

    public static boolean sendMail(MailBean mail) throws MessagingException {
        String to = mail.getToEmail();
        String title = mail.getTitle();
        String emailMessage = mail.getEmailMessage();

        //定义Properties对象,设置环境信息
        Properties props = System.getProperties();

        //设置邮件服务器的地址
        props.setProperty("mail.smtp.host", mail.getMailConfig().getSendServer()); // 指定的smtp服务器
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");//设置发送邮件使用的协议

        //创建Session对象,session对象表示整个邮件的环境信息
        Session session = Session.getInstance(props);
        //设置输出调试信息
        session.setDebug(true);
//        try {
            //Message的实例对象表示一封电子邮件
            MimeMessage message = new MimeMessage(session);
            //设置发件人的地址
            message.setFrom(new InternetAddress(mail.getMailConfig().getSendEmail()));
            //设置主题
            message.setSubject(title);
            //设置邮件的文本内容
//            message.setText("Welcome to JavaMail World!");
            message.setContent((emailMessage), "text/html;charset=utf-8");
            //从session的环境中获取发送邮件的对象
            Transport transport = session.getTransport();
            //连接邮件服务器
            transport.connect(mail.getMailConfig().getSendServer(), mail.getMailConfig().getPort(), mail.getMailConfig().getSendEmail(), mail.getMailConfig().getPassword());
            //设置收件人地址,并发送消息
            transport.sendMessage(message, new Address[]{new InternetAddress(to)});
            // 设置收件人
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));

            transport.close();
            return true;
//        } catch (MessagingException e) {
//            e.printStackTrace();
//            return false;
//        }
    }

//    public static void main(String[] args) throws GeneralSecurityException {
//        String email="shicx@sdkeji.com";
//        String activeCode = "";
//        for (int i = 0;i<6;i++){
//            activeCode=(int)(Math.random()*10)+activeCode;
//        }
//        MailBean mail = new MailBean();
//        mail.setToEmail(email);
//        mail.setTitle("1234");
//        mail.setEmailMessage("66666");
//
//        boolean f = MailUtils.sendMail(email,"账户邮箱激活",
//                "验证码为"+activeCode);
//        System.out.println(f);
//    }
}
